package cn.tedu.mall.order.controller;

import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.JsonResult;
import cn.tedu.mall.order.service.IOmsCartService;
import cn.tedu.mall.order.utils.WebConsts;
import cn.tedu.mall.pojo.order.dto.CartAddDTO;
import cn.tedu.mall.pojo.order.dto.CartUpdateDTO;
import cn.tedu.mall.pojo.order.vo.CartStandardVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/oms/cart")
@Api(tags = "购物车管理模块")
public class OmsCartController {
    @Autowired
    private IOmsCartService omsCartService;
    @PostMapping("/add")
    @ApiOperation("新增sku信息到购物车")
    @PreAuthorize("hasAuthority('ROLE_user')")
    public JsonResult addCart(@Validated CartAddDTO cartAddDTO){
        omsCartService.addCart(cartAddDTO);
        return JsonResult.ok("新增sku到购物车完成");
    }

    @PostMapping("/delete")
    @ApiOperation("根据id删除购物车商品")
    @ApiImplicitParam(value = "要删除的id数组",name = "ids",required = true,dataType = "array")
    @PreAuthorize("hasAuthority('ROLE_user')")
    public JsonResult deleteCartById(Long[] ids){
        omsCartService.removeCart(ids);
        return JsonResult.ok("根据id删除购物车商品完成");
    }

    @PostMapping("/delete/all")
    @ApiOperation("清空当前登录用户的购物车商品信息")
    @PreAuthorize("hasRole('user')")
    public JsonResult removeCartsByUserId(){
        omsCartService.removeAllCarts();
        return JsonResult.ok("购物车清空!");
    }

    @PostMapping("/update/quantity")
    @ApiOperation("修改购物车中sku商品数量")
    @PreAuthorize("hasRole('user')")
    public JsonResult updateQuantity(@Validated CartUpdateDTO cartUpdateDTO){
        omsCartService.updateQuantity(cartUpdateDTO);
        return JsonResult.ok("修改完成");
    }

    @GetMapping("/list")
    @ApiOperation("根据用户id分页查询购物车")
    @ApiImplicitParams({@ApiImplicitParam(value = "页码",name = "page",example = "1"),
                                    @ApiImplicitParam(value = "每页条数",name = "pageSize",example = "2")})
    @PreAuthorize("hasAuthority('ROLE_user')")
    public JsonResult<JsonPage<CartStandardVO>> listCartByPage(
            @RequestParam(required = false,defaultValue = WebConsts.DEFAULT_PAGE) Integer page,
            @RequestParam(required = false,defaultValue = WebConsts.DEFAULT_PAGE_SIZE) Integer pageSize){
        JsonPage<CartStandardVO> jsonPage = omsCartService.listCarts(page,pageSize);
        return JsonResult.ok(jsonPage);
    }
}
